package com.yonyou.gmcc.gateway.web.jwt;

import java.security.Key;  
import java.util.Date;
import java.util.UUID;

import javax.crypto.spec.SecretKeySpec;  
import javax.xml.bind.DatatypeConverter;

import org.apache.log4j.Logger;

import com.yonyou.gmcc.gateway.web.consts.CommonConstants;

import io.jsonwebtoken.Claims;  
import io.jsonwebtoken.JwtBuilder;  
import io.jsonwebtoken.Jwts;  
import io.jsonwebtoken.SignatureAlgorithm;  

public class JwtHelper {
	private static Logger logger=Logger.getLogger(JwtHelper.class);
	public static String getUserName(String jwtToken){
		Claims claims=parseJWT(jwtToken);
		if(claims==null){
			return "";
		}
		String userInfo=(String)claims.get("userName");
		return userInfo;
	}
	public static Claims getClaims(String jwtToken){
		Claims claims=parseJWT(jwtToken);
		return claims;
	}
	public static String getUserId(String jwtToken){
		Claims claims=parseJWT(jwtToken);
		if(claims==null){
			return "";
		}
		String userInfo=(String)claims.get("userid");
		return userInfo;
	}
	public static String getUserId(Claims claims){
		String userInfo=(String)claims.get("userid");
		return userInfo;
	}
	public static String getUserName(Claims claims){
		String userInfo=(String)claims.get("userName");
		return userInfo;
	}
	public static Claims parseJWT(String jwtToken){  
		try{
	    	Claims claims = Jwts.parser()        
	  	    	   .setSigningKey(DatatypeConverter.parseBase64Binary(CommonConstants.JwtSecret))
	  	    	   .parseClaimsJws(jwtToken).getBody();
	  	
	     	return claims;
		}catch(Exception ex){
	   	    logger.info("-------------parseJWT error="+ex.getMessage());
			return null;
		}
		
    }  
      
    public static String createJWT(String name, String userId, String role,   
            String audience, String issuer, long TTLMillis)   
    {  
   	 
   	//The JWT signature algorithm we will be using to sign the token
   	SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
   	 
   	long nowMillis = System.currentTimeMillis();
   	Date now = new Date(nowMillis);
   	 
   	//We will sign our JWT with our ApiKey secret
   	byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(CommonConstants.JwtSecret);
   	Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
   	  //Let's set the JWT Claims
   	JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")  
               .claim("role", "role")  
               .claim("userName",name)  
               .claim("userid", userId)  
               .setIssuedAt(now)
               .setId(UUID.randomUUID().toString())
               //.setSubject(subject)
               .setIssuer(issuer)
               .signWith(signatureAlgorithm, signingKey);
   	 
   	//if it has been specified, let's add the expiration
   	if (TTLMillis >= 0) {
   	    long expMillis = nowMillis + TTLMillis*60*1000;
   	    Date exp = new Date(expMillis);
   	    builder.setExpiration(exp);
   	    logger.info("-------------date="+exp);
   	}
   	 
   	//Builds the JWT and serializes it to a compact, URL-safe string
   	return builder.compact();
   	/*
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;  
           
        long nowMillis = System.currentTimeMillis();  
        Date now = new Date(nowMillis);  
           
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(CommonConstants.JwtSecret);  
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());  
           
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")  
                                        .claim("role", role)  
                                        .claim("md5openid", name)  
                                        .claim("userid", userId)  
                                        .setIssuer(issuer)  
                                        .setAudience(audience)  
                                        .signWith(signatureAlgorithm, signingKey);  
         //添加Token过期时间  
        if (TTLMillis >= 0) {  
            long expMillis = nowMillis + TTLMillis;  
            Date exp = new Date(expMillis);  
            builder.setExpiration(exp).setNotBefore(now);  
        }  
           
         //生成JWT  
        return builder.compact();  */
    }   
}
